<?php
/**
 * Add a new Proffessional Experience
 *
 * @author Xavier VILAIN
 */
use Hive\Ressource\Wish\Localization;
use Fox\Core\Errors;
use Fox\Generator;
use Hive\Ressource;
use Hive\Ressource\Experience;
use Fox\Popup;
use Fox\Html\Screen;

$xview = Xview::instance();
$rid = $xview->val('rid');
$wid = $xview->val('wid');
/* @var $contact Hive\Ressource */
$contact = Xview::instance()->component('ressource', 'object');
$wish = $contact->findWishes($wid.':'.$rid);
$data = $wish->getData();
$data['localization'] = $wish->formatLocalizationTokens();
$screen = new Screen('sWish','update',null,true,Generator::ajaxReload('contentCol',
			Generator::url('ressource','wishes',null,array('rid' => $rid))));
$block = $xview->component('ressource','wish');
$screen->add($block)->noLegend();
$screen->initialize($data);

if($screen->submitted()) {
	$fields = $screen->get();
	if(!$screen->errors()) {
		try {
			$label = $fields['joblist'];
			$wish->setFields($fields);
			// Current Localization
			foreach($wish->localizations() as $localization){
				$localizations[$localization->code] = $localization;
			}
			// Handle Localization
			if(!empty($fields['localization'])) {
				foreach(Localization::parseTokens($fields['localization']) as $tokenData){
					$localization = $wish->findLocalizations($wid.':'.$rid.':'.$tokenData['code']);
					if($localization->exists()) {
						unset($localizations[$tokenData['code']]);
						continue;
					} else {
						$localization->setFields($tokenData);
						$wish->addToLocalizations($localization);
					}
				}
			}
			if(isset($localizations)) {
				foreach($localizations as $localization) {
						$wish->deleteFromLocalizations($localization);
				}
			}
			$contact->replaceWishes($wish);
			$cdate = null;
			// Update Current Wish Flag
			foreach($contact->wishes() as $wish) {
				$current = $wish->current;
				if($wish->cdate > $cdate ) {
					$cdate = $wish->cdate;
					$currentWish = $wish;
				}
				if($current) {
					$oldCurrentWish = $wish; 
				}
			}
			if($currentWish->did != $oldCurrentWish->did) {
				$oldCurrentWish->current = 0;
				$contact->replaceWishes($oldCurrentWish);
				$currentWish->current = 1;
				$contact->replaceWishes($currentWish);
			}
			$contact->prepareUpdate(Ressource::CHANGE_WISHES);
			$contact->update();
			Fox\Message::Success(Msg(\Fox\Msg::BUNDLE,\Fox\Msg::MSG_UPDATE,$label));
			$xview->messages(false,true);
			exit;
		}
		catch (Fox\Object\Exception\Save $e)
		{
			Errors::pushMessage($e);
		}
		catch (Fox\Object\Exception\NotExist $e)
		{
			Fox\Message::Error($e->message());
		}
	}
}
$popup = new Popup("add",Msg(Hive::BUNDLE,Hive::MSG_UPDATE_WISH),$screen,700);
echo $popup->display();